package com.chinapost.service.impl;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.excelUtil.ExcelUtil;
import com.chinapost.po.Tdept;
import com.chinapost.po.Tfczy;
import com.chinapost.po.Tuser;
import com.chinapost.po.Twdxx;
import com.chinapost.service.FczyServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Fczy;

@Service("fczyService")
public class FczyServiceImpl implements FczyServiceI {

	@Autowired
	private BaseDaoI<Tfczy> fczyDao;
	@Autowired
	private BaseDaoI<Tdept> deptDao;
	@Autowired
	private BaseDaoI<Twdxx> wdxxDao;
	@Autowired
	private BaseDaoI<Tuser> userDao;

	@Override
	public DataGrid datagrid(Fczy fczy) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(fczy)));
		dg.setTotal(total(fczy));
		return dg;
	}

	private Long total(Fczy fczy) {
		String hql = "select count(*) from Tfczy t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(fczy, hql, params);
		return fczyDao.count(hql, params);
	}

	private List<Tfczy> find(Fczy fczy) {
		String hql = "from Tfczy t where 1=1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(fczy, hql, params);
		if (fczy.getOrder() != null && fczy.getSort() != null) {
			hql += " order by " + fczy.getSort() + " " + fczy.getOrder();
		}
		return fczyDao.find(hql, params, fczy.getPage(), fczy.getRows());
	}

	private List<Fczy> listRows(List<Tfczy> lt) {
		List<Fczy> rows = new ArrayList<Fczy>();
		if (lt != null && lt.size() > 0) {
			for (Tfczy t : lt) {
				Fczy sub = new Fczy();
				BeanUtils.copyProperties(t, sub);
				sub.setDeptId(t.getTdept().getCid());
				sub.setDeptName(t.getTdept().getCname());
				sub.setWdid(t.getTwdxx().getCid());
				sub.setWdname(t.getTwdxx().getCname());
				rows.add(sub);
			}
		}
		return rows;
	}

	private String addWhere(Fczy fczy, String hql, Map<String, Object> params) {
		if (fczy != null && fczy.getCid() != null && !fczy.getCid().trim().equals("")) {
			hql += " and t.cid = :id ";
			params.put("id", fczy.getCid());
		}
		if (fczy != null && fczy.getWdname() != null && !fczy.getWdname().trim().equals("")) {
			hql += " and t.twdxx.cname like :wdname ";
			params.put("wdname", "%%" + fczy.getWdname() + "%%");
		}
		if (fczy != null && !StringUtils.isEmpty(fczy.getWdid())) {
			hql += " and t.twdxx.cid = :wdid";
			params.put("wdid", fczy.getWdid());
		}
		if (fczy != null && fczy.getDeptIds() != null && fczy.getDeptIds().size() > 0) {
			hql += " and t.tdept.cid in(:deptids)";
			params.put("deptids", fczy.getDeptIds());
		}
		return hql;
	}

	@Override
	public List<Fczy> listFczy() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void add(Fczy fczy) {
		Tfczy tfczy = new Tfczy();
		Date d = new Date();
		BeanUtils.copyProperties(fczy, tfczy);
		tfczy.setCid(UUID.randomUUID().toString());
		tfczy.setCcreatedate(new Timestamp(d.getTime()));
		tfczy.setCmodifydate(new Timestamp(d.getTime()));
		tfczy.setTdept(deptDao.get(Tdept.class, fczy.getDeptId()));
		tfczy.setTwdxx(wdxxDao.get(Twdxx.class, fczy.getWdid()));
		if (!StringUtils.isEmpty(fczy.getCreateUserId())) {
			tfczy.setTuserByCcreateuserid(userDao.get(Tuser.class, fczy.getCreateUserId()));
			tfczy.setTuserByCmodifyuserid(userDao.get(Tuser.class, fczy.getCreateUserId()));
		}
		fczyDao.save(tfczy);
	}

	@Override
	public void edit(Fczy fczy) {
		Tfczy t = fczyDao.get(Tfczy.class, fczy.getCid());
		BeanUtils.copyProperties(fczy, t, new String[] { "ccreatedate" });
		Date d = new Date();
		t.setCmodifydate(new Timestamp(d.getTime()));
		t.setTdept(deptDao.get(Tdept.class, fczy.getDeptId()));
		t.setTwdxx(wdxxDao.get(Twdxx.class, fczy.getWdid()));
		if (!StringUtils.isEmpty(fczy.getModifyUserId())) {
			t.setTuserByCmodifyuserid(userDao.get(Tuser.class, fczy.getModifyUserId()));
		}
	}

	@Override
	public void delete(Fczy fczy) {
		String cids = "";
		if (fczy.getIds() != null) {
			String ids = fczy.getIds();
			for (String cid : ids.split(",")) {
				cids += "'" + cid + "'" + ",";
			}
			cids = cids.substring(0, cids.length() - 1);
			String hql = "delete Tfczy t where t.cid in (" + cids + ")";
			fczyDao.executeHql(hql);
		}

	}

	@Override
	public int addFczys(Fczy fczy) {
		int i = 0;
		String[] fields = { "wdname", "czczyf" };
		if (fczy != null && !fczy.getFilename().isEmpty()) {
			ExcelUtil eu = new ExcelUtil();
			List<ArrayList<String>> fczyList = eu.read(fczy.getFilename());
			Tdept tdept = deptDao.get(Tdept.class, fczy.getDeptId());
			if (tdept != null) {
				for (ArrayList<String> row : fczyList) {
					String wdname = row.get(0).trim();
					if (!StringUtils.isEmpty(wdname)) {
						String hql = "from Twdxx t where t.cname = :wdname";
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("wdname", wdname);
						Twdxx wd = wdxxDao.get(hql, params);
						if (wd != null) {
							Tfczy t = new Tfczy();
							t.setCid(UUID.randomUUID().toString());
							t.setTdept(tdept);
							t.setTwdxx(wd);
							Date d = new Date();
							t.setCcreatedate(new Timestamp(d.getTime()));
							t.setCmodifydate(new Timestamp(d.getTime()));
							for (int n = 1; n < row.size(); n++) {
								try {
									org.apache.commons.beanutils.BeanUtils.setProperty(t, fields[n], row.get(n).trim());
								} catch (IllegalAccessException e) {
									e.printStackTrace();
								} catch (InvocationTargetException e) {
									e.printStackTrace();
								}
							}
							if (!StringUtils.isEmpty(fczy.getCreateUserId())) {
								t.setTuserByCcreateuserid(userDao.get(Tuser.class, fczy.getCreateUserId()));
								t.setTuserByCmodifyuserid(userDao.get(Tuser.class, fczy.getCreateUserId()));
							}
							fczyDao.save(t);
							i++;
						}
					}
				}
			}
			File f = new File(fczy.getFilename());
			if (f.exists() && f.isFile()) {
				f.delete();
			}
		}
		return i;
	}

}
